<%#
 Copyright 2013-2025 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.web.rest;
<%_
let saveMethod = 'save';
if (!reactive && databaseTypeSql) {
    saveMethod = 'saveAndFlush';
}
_%>
import <%= packageName %>.IntegrationTest;

<%_ if (databaseTypeSql && reactive) { _%>
import <%= packageName %>.config.Constants;
<%_ } _%>
<%_ if (!databaseTypeCassandra && !databaseTypeCouchbase) { _%>
import <%= packageName %>.domain.Authority;
<%_ } _%>
import <%= user.entityAbsoluteClass %>;
<%_ if (databaseTypeSql && reactive) { _%>
import <%= packageName %>.repository.AuthorityRepository;
<%_ } _%>
import <%= packageName %>.repository.UserRepository;
<%_ if (!requiresDeleteAllUsers) { _%>
import <%= packageName %>.service.UserService;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>
import <%= packageName %>.repository.search.UserSearchRepository;
<%_ } _%>
import <%= packageName %>.security.AuthoritiesConstants;
import <%= packageName %>.service.dto.<%= user.adminUserDto %>;
<%_ if (databaseTypeSql && reactive) { _%>
import <%= packageName %>.repository.EntityManager;
<%_ } _%>
import <%= packageName %>.service.mapper.UserMapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
<%_ if (reactive) { _%>
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
<%_ } else { _%>
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
<%_ } _%>
<%_ if (cacheProviderAny) { _%>
import org.springframework.cache.CacheManager;
import org.springframework.cache.Cache;
<%_ } _%>
<%_ if (cacheProviderMemcached) { _%>
import org.springframework.cache.support.NoOpCacheManager;
<%_ } _%>
import org.springframework.http.MediaType;
<%_ if (databaseTypeCouchbase) { _%>
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.TestSecurityContextHolder;
<%_ } _%>
import org.springframework.security.test.context.support.WithMockUser;
<%_ if (reactive) { _%>
import org.springframework.test.web.reactive.server.WebTestClient;
<%_ } else { _%>
import org.springframework.test.web.servlet.MockMvc;
<%_ } _%>
<%_ if (databaseTypeSql && !reactive) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>
<%_ if (reactive && searchEngineElasticsearch) { _%>
import reactor.core.publisher.Mono;
<%_ } _%>

<%_ if (databaseTypeSql && !reactive) { _%>
import jakarta.persistence.EntityManager;
<%_ } _%>
import java.util.*;
import java.util.function.Consumer;
<%_ if (databaseTypeCassandra || databaseTypeCouchbase) { _%>
import java.util.stream.Collectors;
import java.util.stream.Stream;
<%_ } _%>

import static org.assertj.core.api.Assertions.assertThat;
<%_ if (reactive && searchEngineElasticsearch) { _%>
import static org.mockito.Mockito.*;
<%_ } _%>
<%_ if (reactive && authenticationUsesCsrf) { _%>
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf;
<%_ } else if (!reactive) { _%>
import static org.hamcrest.Matchers.hasItem;
  <%_ if (authenticationUsesCsrf) { _%>
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
  <%_ } _%>
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
<%_ } _%>

/**
 * Integration tests for the {@link UserResource} REST controller.
 */
<%_ if (reactive) { _%>
@AutoConfigureWebTestClient(timeout = IntegrationTest.DEFAULT_TIMEOUT)
<%_ } else { _%>
@AutoConfigureMockMvc
<%_ } _%>
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
@IntegrationTest
class UserResourceIT {

    private static final String DEFAULT_LOGIN = "johndoe";
<%_ if (!authenticationTypeOauth2) { _%>
    private static final String UPDATED_LOGIN = "jhipster";
<%_ } _%>

<%_ if (databaseTypeCouchbase) { _%>
    private static final String DEFAULT_ID = DEFAULT_LOGIN;
<%_ } else { _%>
    private static final <%= user.primaryKey.type %> DEFAULT_ID = <%- user.primaryKey.javaSampleValues[0] %>;
<%_ } _%>

    private static final String DEFAULT_EMAIL = "johndoe@localhost";
<%_ if (!authenticationTypeOauth2) { _%>
    private static final String UPDATED_EMAIL = "jhipster@localhost";
<%_ } _%>

    private static final String DEFAULT_FIRSTNAME = "john";
<%_ if (!authenticationTypeOauth2) { _%>
    private static final String UPDATED_FIRSTNAME = "jhipsterFirstName";
<%_ } _%>

    private static final String DEFAULT_LASTNAME = "doe";
<%_ if (!authenticationTypeOauth2) { _%>
    private static final String UPDATED_LASTNAME = "jhipsterLastName";
<%_ } _%>

<%_ if (!databaseTypeCassandra) { _%>
    private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
  <%_ if (!authenticationTypeOauth2) { _%>
    private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40";
  <%_ } _%>

<%_ } _%>
    private static final String DEFAULT_LANGKEY = "en";
<%_ if (!authenticationTypeOauth2) { _%>
    private static final String UPDATED_LANGKEY = "fr";
<%_ } _%>

    @Autowired
    private ObjectMapper om;

    @Autowired
    private UserRepository userRepository;
<%_ if (!requiresDeleteAllUsers) { _%>

    @Autowired
    private UserService userService;
<%_ } _%>
<%_ if (databaseTypeSql && reactive) { _%>

    @Autowired
    private AuthorityRepository authorityRepository;
<%_ } _%>
<%_ if (searchEngineElasticsearch) { _%>

    @Autowired
    private UserSearchRepository userSearchRepository;
<%_ } _%>

    @Autowired
    private UserMapper userMapper;
<%_ if (databaseTypeSql) { _%>

    @Autowired
    private EntityManager em;
<%_ } _%>
<%_ if (cacheProviderAny) { _%>

    @Autowired
    private CacheManager cacheManager;
<%_ } _%>

    @Autowired
<%_ if (reactive) { _%>
    private WebTestClient webTestClient;
<%_ } else { _%>
    private MockMvc restUserMockMvc;
<%_ } _%>

    private <%= user.persistClass %> user;

<%_ if (!databaseTypeCassandra && !requiresDeleteAllUsers) { _%>
    private Long numberOfUsers;

    @BeforeEach
    void countUsers() {
        numberOfUsers = userRepository.count()<%- reactorBlock %>;
    }

<%_ } _%>
<%_ if (reactive && authenticationUsesCsrf) { _%>
    @BeforeEach
    void setupCsrf() {
        webTestClient = webTestClient.mutateWith(csrf());
    }

<%_ } _%>
    /**
     * Create a User.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which has a required relationship to the User entity.
     */
    public static <%= user.persistClass %> createEntity() {
        <%= user.persistClass %> persistUser = new <%= user.persistClass %>();
<%_ if (databaseTypeCassandra || (authenticationTypeOauth2 && !databaseTypeCouchbase)) { _%>
        persistUser.setId(UUID.randomUUID().toString());
<%_ } _%>
        persistUser.setLogin(DEFAULT_LOGIN<% if (databaseTypeSql) { %> + RandomStringUtils.insecure().nextAlphabetic(5)<% } %>);
<%_ if (!authenticationTypeOauth2) { _%>
        persistUser.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60));
<%_ } _%>
        persistUser.setActivated(true);
        persistUser.setEmail(<% if (databaseTypeSql) { %>RandomStringUtils.insecure().nextAlphabetic(5) + <% } %>DEFAULT_EMAIL);
        persistUser.setFirstName(DEFAULT_FIRSTNAME);
        persistUser.setLastName(DEFAULT_LASTNAME);
<%_ if (!databaseTypeCassandra) { _%>
        persistUser.setImageUrl(DEFAULT_IMAGEURL);
<%_ } _%>
        persistUser.setLangKey(DEFAULT_LANGKEY);
<%_ if (databaseTypeSql && reactive) { _%>
        persistUser.setCreatedBy(Constants.SYSTEM);
<%_ } _%>
        return persistUser;
    }
<%_ if (databaseTypeSql && reactive) { _%>

    /**
     * Delete all the users from the database.
     */
    public static void deleteEntities(EntityManager em) {
    }
<%_ } _%>

    /**
     * Setups the database with one user.
     */
    public static <%= user.persistClass %> initTestUser() {
        <%= user.persistClass %> persistUser = createEntity();
<%_ if (databaseTypeSql) { _%>
        persistUser.setLogin(DEFAULT_LOGIN);
        persistUser.setEmail(DEFAULT_EMAIL);
<%_ } _%>
        return persistUser;
    }

    @BeforeEach
    void initTest() {
        user = initTestUser();
    }

    @AfterEach
    void cleanupAndCheck() {
<%_ if (requiresDeleteAllUsers) { _%>
    <%_ if (databaseTypeSql && reactive) { _%>
        userRepository.deleteAllUserAuthorities()<%- reactorBlock %>;
    <%_ } _%>
        userRepository.deleteAll()<%- reactorBlock %>;
<%_ } else { _%>
        userService.deleteUser(DEFAULT_LOGIN)<%- reactorBlock %>;
        userService.deleteUser(UPDATED_LOGIN)<%- reactorBlock %>;
        userService.deleteUser(user.getLogin())<%- reactorBlock %>;
        userService.deleteUser("anotherlogin")<%- reactorBlock %>;
<%_ } _%>
<%_ if (!databaseTypeCassandra && !requiresDeleteAllUsers) { _%>
        assertThat(userRepository.count()<%- reactorBlock %>).isEqualTo(numberOfUsers);
        numberOfUsers = null;
<%_ } _%>
<%_ if (cacheProviderAny) { _%>
        cacheManager.getCacheNames().stream()
            .map(cacheName -> this.cacheManager.getCache(cacheName))
            .filter(Objects::nonNull)
            .forEach(Cache::invalidate);
<%_ } _%>
    }
<%_ if (!authenticationTypeOauth2) { _%>

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void createUser() throws Exception {
        // Create the User
        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
        userDTO.setLogin(DEFAULT_LOGIN);
        userDTO.setFirstName(DEFAULT_FIRSTNAME);
        userDTO.setLastName(DEFAULT_LASTNAME);
        userDTO.setEmail(DEFAULT_EMAIL);
        userDTO.setActivated(true);
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(DEFAULT_IMAGEURL);
  <%_ } _%>
        userDTO.setLangKey(DEFAULT_LANGKEY);
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

  <%_ if (reactive) { _%>
        var returned<%- restClass %> = webTestClient.post().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(userDTO))
            .exchange()
            .expectStatus().isCreated()
            .expectBody(<%= user.adminUserDto %>.class)
            .returnResult()
            .getResponseBody();
  <%_ } else { _%>
        var returned<%- restClass %> = om.readValue(
            restUserMockMvc.perform(post("/api/admin/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
                .with(csrf())<% } %>)
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            <%= user.adminUserDto %>.class
        );
  <%_ } _%>

        <%= user.persistClass %> convertedUser = userMapper.userDTOToUser(returned<%- restClass %>);
        // Validate the returned User
        assertThat(convertedUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
        assertThat(convertedUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
        assertThat(convertedUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
        assertThat(convertedUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
  <%_ if (!databaseTypeCassandra) { _%>
        assertThat(convertedUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
  <%_ } _%>
        assertThat(convertedUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void createUserWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = userRepository.findAll()<% if (reactive) { %>
            .collectList().block()<% } %>.size();

        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
  <%_ if (databaseTypeCassandra) { _%>
        userDTO.setId(UUID.randomUUID().toString());
  <%_ } else if (databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
        userDTO.setId("1L");
  <%_ } else { _%>
        userDTO.setId(DEFAULT_ID);
  <%_ } _%>
        userDTO.setLogin(DEFAULT_LOGIN);
        userDTO.setFirstName(DEFAULT_FIRSTNAME);
        userDTO.setLastName(DEFAULT_LASTNAME);
        userDTO.setEmail(DEFAULT_EMAIL);
        userDTO.setActivated(true);
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(DEFAULT_IMAGEURL);
  <%_ } _%>
        userDTO.setLangKey(DEFAULT_LANGKEY);
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        // An entity with an existing ID cannot be created, so this API call must fail
  <%_ if (reactive) { _%>
        webTestClient.post().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(userDTO))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        restUserMockMvc.perform(post("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isBadRequest());
  <%_ } _%>

        // Validate the User in the database
        assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void createUserWithExistingLogin() throws Exception {
        // Initialize the database
        userRepository.<%= saveMethod %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ if (searchEngineElasticsearch) { _%>
        userSearchRepository.save(user)<% if (reactive) { %>.block()<% } %>;
  <%_ } _%>
        int databaseSizeBeforeCreate = userRepository.findAll()<% if (reactive) { %>
            .collectList().block()<% } %>.size();

        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
        userDTO.setLogin(DEFAULT_LOGIN);// this login should already be used
        userDTO.setFirstName(DEFAULT_FIRSTNAME);
        userDTO.setLastName(DEFAULT_LASTNAME);
        userDTO.setEmail("anothermail@localhost");
        userDTO.setActivated(true);
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(DEFAULT_IMAGEURL);
  <%_ } _%>
        userDTO.setLangKey(DEFAULT_LANGKEY);
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        // Create the User
  <%_ if (reactive) { _%>
        webTestClient.post().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(userDTO))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        restUserMockMvc.perform(post("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isBadRequest());
  <%_ } _%>

        // Validate the User in the database
        assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void createUserWithExistingEmail() throws Exception {
        // Initialize the database
        userRepository.<%= saveMethod %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ if (searchEngineElasticsearch) { _%>
        userSearchRepository.save(user)<% if (reactive) { %>.block()<% } %>;
  <%_ } _%>
        int databaseSizeBeforeCreate = userRepository.findAll()<% if (reactive) { %>
            .collectList().block()<% } %>.size();

        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
        userDTO.setLogin("anotherlogin");
        userDTO.setFirstName(DEFAULT_FIRSTNAME);
        userDTO.setLastName(DEFAULT_LASTNAME);
        userDTO.setEmail(DEFAULT_EMAIL); // this email should already be used
        userDTO.setActivated(true);
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(DEFAULT_IMAGEURL);
  <%_ } _%>
        userDTO.setLangKey(DEFAULT_LANGKEY);
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

        // Create the User
  <%_ if (reactive) { _%>
        webTestClient.post().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(user))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        restUserMockMvc.perform(post("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isBadRequest());
  <%_ } _%>

        // Validate the User in the database
        assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeCreate));
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void getAllUsers()<% if (!reactive) { %> throws Exception<% } %> {
        // Initialize the database
        userRepository.<% if (databaseTypeSql && reactive && authenticationTypeOauth2) { %>create<% } else { %><%= saveMethod %><% } %>(user)<% if (reactive) { %>.block()<% } %>;

        // Get all the users
  <%_ if (reactive) { _%>
        <%= user.adminUserDto %> foundUser = webTestClient.get().uri("/api/admin/users<% if (user.primaryKey.typeNumeric) { %>?sort=id,desc<% } %>")
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .returnResult(<%= user.adminUserDto %>.class).getResponseBody()<% if (!user.primaryKey.typeNumeric) { %>.filter(e -> DEFAULT_LOGIN.equals(e.getLogin()))<% } %>.blockFirst();
        assertThat(foundUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
        assertThat(foundUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
        assertThat(foundUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
        assertThat(foundUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
    <%_ if (!databaseTypeCassandra) { _%>
        assertThat(foundUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
    <%_ } _%>
        assertThat(foundUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
  <%_ } else { _%>
        restUserMockMvc.perform(get("/api/admin/users<% if (user.primaryKey.typeNumeric) { %>?sort=id,desc<% } %>")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
            .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
            .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
            .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
    <%_ if (!databaseTypeCassandra) { _%>
            .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
    <%_ } _%>
            .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
  <%_ } _%>
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void getUser()<% if (!reactive) { %> throws Exception<% } %> {
        // Initialize the database
        userRepository.<% if (databaseTypeSql && reactive && authenticationTypeOauth2) { %>create<% } else { %><%= saveMethod %><% } %>(user)<% if (reactive) { %>.block()<% } %>;

  <%_ if (searchEngineElasticsearch) { _%>
        userSearchRepository.save(user);
  <%_ } _%>
  <%_ if (cacheProviderAny) { _%>

        assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin(), <%= user.persistClass %>.class)).isNull();
  <%_ } _%>

        // Get the user
  <%_ if (reactive) { _%>
        webTestClient.get().uri("/api/admin/users/{login}", user.getLogin())
            .exchange()
            .expectStatus().isOk()
            .expectHeader().contentType(MediaType.APPLICATION_JSON)
            .expectBody()
            .jsonPath("$.login").isEqualTo(user.getLogin())
            .jsonPath("$.firstName").isEqualTo(DEFAULT_FIRSTNAME)
            .jsonPath("$.lastName").isEqualTo(DEFAULT_LASTNAME)
            .jsonPath("$.email").isEqualTo(DEFAULT_EMAIL)
    <%_ if (!databaseTypeCassandra) { _%>
            .jsonPath("$.imageUrl").isEqualTo(DEFAULT_IMAGEURL)
    <%_ } _%>
            .jsonPath("$.langKey").isEqualTo(DEFAULT_LANGKEY);
  <%_ } else { _%>
        restUserMockMvc.perform(get("/api/admin/users/{login}", user.getLogin()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.login").value(user.getLogin()))
            .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME))
            .andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME))
            .andExpect(jsonPath("$.email").value(DEFAULT_EMAIL))
    <%_ if (!databaseTypeCassandra) { _%>
            .andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL))
    <%_ } _%>
            .andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY));
  <%_ } _%>

  <%_ if (cacheProviderMemcached) { _%>
        if (!(cacheManager instanceof NoOpCacheManager)) {
            assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNotNull();
        }
  <%_ } else if (cacheProviderAny) { _%>
        assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin(), <%= user.persistClass %>.class)).isNotNull();
  <%_ } _%>
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void getNonExistingUser()<% if (!reactive) { %> throws Exception<% } %> {
  <%_ if (reactive) { _%>
        webTestClient.get().uri("/api/admin/users/unknown")
            .exchange()
            .expectStatus().isNotFound();
  <%_ } else { _%>
        restUserMockMvc.perform(get("/api/admin/users/unknown"))
            .andExpect(status().isNotFound());
  <%_ } _%>
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void updateUser() throws Exception {
        // Initialize the database
        userRepository.<%= saveMethod %>(user)<% if (reactive) { %>.block()<% } %>;
        int databaseSizeBeforeUpdate = userRepository.findAll()<% if (reactive) { %>
            .collectList().block()<% } %>.size();

        // Update the user
        <%= user.persistClass %> updatedUser = userRepository.findById(user.getId()).<% if (reactive) { %>block<% } else { %>orElseThrow<% } %>();

        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
        userDTO.setId(updatedUser.getId());
        userDTO.setLogin(updatedUser.getLogin());
        userDTO.setFirstName(UPDATED_FIRSTNAME);
        userDTO.setLastName(UPDATED_LASTNAME);
        userDTO.setEmail(UPDATED_EMAIL);
        userDTO.setActivated(updatedUser.isActivated());
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(UPDATED_IMAGEURL);
  <%_ } _%>
        userDTO.setLangKey(UPDATED_LANGKEY);
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setCreatedBy(updatedUser.getCreatedBy());
        userDTO.setCreatedDate(updatedUser.getCreatedDate());
        userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy());
        userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate());
  <%_ } _%>
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

  <%_ if (reactive) { _%>
        webTestClient.put().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(userDTO))
            .exchange()
            .expectStatus().isOk();
  <%_ } else { _%>
        restUserMockMvc.perform(put("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isOk());
  <%_ } _%>

        // Validate the User in the database
        assertPersistedUsers(users -> {
            assertThat(users).hasSize(databaseSizeBeforeUpdate);
            <%= user.persistClass %> testUser = users.stream().filter(usr -> usr.getId().equals(updatedUser.getId())).findFirst().orElseThrow();
            assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
            assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
            assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
  <%_ if (!databaseTypeCassandra) { _%>
            assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
  <%_ } _%>
            assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
        });
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void updateUserLogin() throws Exception {
        // Initialize the database
        userRepository.<%= saveMethod %>(user)<% if (reactive) { %>.block()<% } %>;
        int databaseSizeBeforeUpdate = userRepository.findAll()<% if (reactive) { %>
            .collectList().block()<% } %>.size();

        // Update the user
        <%= user.persistClass %> updatedUser = userRepository.findById(user.getId()).<% if (reactive) { %>block<% } else { %>orElseThrow<% } %>();

        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
        userDTO.setId(updatedUser.getId());
        userDTO.setLogin(UPDATED_LOGIN);
        userDTO.setFirstName(UPDATED_FIRSTNAME);
        userDTO.setLastName(UPDATED_LASTNAME);
        userDTO.setEmail(UPDATED_EMAIL);
        userDTO.setActivated(updatedUser.isActivated());
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(UPDATED_IMAGEURL);
  <%_ } _%>
        userDTO.setLangKey(UPDATED_LANGKEY);
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setCreatedBy(updatedUser.getCreatedBy());
        userDTO.setCreatedDate(updatedUser.getCreatedDate());
        userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy());
        userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate());
  <%_ } _%>
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

  <%_ if (reactive) { _%>
        webTestClient.put().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(userDTO))
            .exchange()
            .expectStatus().isOk();
  <%_ } else { _%>
        restUserMockMvc.perform(put("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isOk());
  <%_ } _%>

        // Validate the User in the database
        assertPersistedUsers(users -> {
            assertThat(users).hasSize(databaseSizeBeforeUpdate);
            <%= user.persistClass %> testUser = users.stream().filter(usr -> usr.getId().equals(updatedUser.getId())).findFirst().orElseThrow();
            assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN);
            assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
            assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
            assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
  <%_ if (!databaseTypeCassandra) { _%>
            assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
  <%_ } _%>
            assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
        });
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void updateUserExistingEmail() throws Exception {
        // Initialize the database with 2 users
        userRepository.<%= saveMethod %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ if (searchEngineElasticsearch) { _%>
        userSearchRepository.save(user);
  <%_ } _%>

        <%= user.persistClass %> anotherUser = new <%= user.persistClass %>();
  <%_ if (databaseTypeCassandra) { _%>
        anotherUser.setId(UUID.randomUUID().toString());
  <%_ } _%>
        anotherUser.setLogin("jhipster");
        anotherUser.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60));
        anotherUser.setActivated(true);
        anotherUser.setEmail("jhipster@localhost");
        anotherUser.setFirstName("java");
        anotherUser.setLastName("hipster");
  <%_ if (!databaseTypeCassandra) { _%>
        anotherUser.setImageUrl("");
  <%_ } _%>
        anotherUser.setLangKey("en");
  <%_ if (databaseTypeSql && reactive) { _%>
        anotherUser.setCreatedBy(Constants.SYSTEM);
  <%_ } _%>
        userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(anotherUser)<% if (reactive) { %>.block()<% } %>;
  <%_ if (searchEngineElasticsearch) { _%>
        userSearchRepository.save(anotherUser);
  <%_ } _%>

        // Update the user
        <%= user.persistClass %> updatedUser = userRepository.findById(user.getId()).<% if (reactive) { %>block<% } else { %>orElseThrow<% } %>();

        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
        userDTO.setId(updatedUser.getId());
        userDTO.setLogin(updatedUser.getLogin());
        userDTO.setFirstName(updatedUser.getFirstName());
        userDTO.setLastName(updatedUser.getLastName());
        userDTO.setEmail("jhipster@localhost"); // this email should already be used by anotherUser
        userDTO.setActivated(updatedUser.isActivated());
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(updatedUser.getImageUrl());
  <%_ } _%>
        userDTO.setLangKey(updatedUser.getLangKey());
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setCreatedBy(updatedUser.getCreatedBy());
        userDTO.setCreatedDate(updatedUser.getCreatedDate());
        userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy());
        userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate());
  <%_ } _%>
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

  <%_ if (reactive) { _%>
        webTestClient.put().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(userDTO))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        restUserMockMvc.perform(put("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isBadRequest());
  <%_ } _%>
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void updateUserExistingLogin() throws Exception {
        // Initialize the database
        userRepository.<%= saveMethod %>(user)<% if (reactive) { %>.block()<% } %>;
  <%_ if (searchEngineElasticsearch) { _%>
        userSearchRepository.save(user);
  <%_ } _%>

        <%= user.persistClass %> anotherUser = new <%= user.persistClass %>();
  <%_ if (databaseTypeCassandra) { _%>
        anotherUser.setId(UUID.randomUUID().toString());
  <%_ } _%>
        anotherUser.setLogin("jhipster");
        anotherUser.setPassword(RandomStringUtils.insecure().nextAlphanumeric(60));
        anotherUser.setActivated(true);
        anotherUser.setEmail("jhipster@localhost");
        anotherUser.setFirstName("java");
        anotherUser.setLastName("hipster");
  <%_ if (!databaseTypeCassandra) { _%>
        anotherUser.setImageUrl("");
  <%_ } _%>
        anotherUser.setLangKey("en");
  <%_ if (databaseTypeSql && reactive) { _%>
        anotherUser.setCreatedBy(Constants.SYSTEM);
  <%_ } _%>
        userRepository.save<% if (databaseTypeSql && !reactive) { %>AndFlush<% } %>(anotherUser)<% if (reactive) { %>.block()<% } %>;
  <%_ if (searchEngineElasticsearch) { _%>
        userSearchRepository.save(anotherUser);
  <%_ } _%>

        // Update the user
        <%= user.persistClass %> updatedUser = userRepository.findById(user.getId()).<% if (reactive) { %>block<% } else { %>orElseThrow<% } %>();

        <%= user.adminUserDto %> userDTO = new <%= user.adminUserDto %>();
        userDTO.setId(updatedUser.getId());
        userDTO.setLogin("jhipster"); // this login should already be used by anotherUser
        userDTO.setFirstName(updatedUser.getFirstName());
        userDTO.setLastName(updatedUser.getLastName());
        userDTO.setEmail(updatedUser.getEmail());
        userDTO.setActivated(updatedUser.isActivated());
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setImageUrl(updatedUser.getImageUrl());
  <%_ } _%>
        userDTO.setLangKey(updatedUser.getLangKey());
  <%_ if (!databaseTypeCassandra) { _%>
        userDTO.setCreatedBy(updatedUser.getCreatedBy());
        userDTO.setCreatedDate(updatedUser.getCreatedDate());
        userDTO.setLastModifiedBy(updatedUser.getLastModifiedBy());
        userDTO.setLastModifiedDate(updatedUser.getLastModifiedDate());
  <%_ } _%>
        userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));

  <%_ if (reactive) { _%>
        webTestClient.put().uri("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(om.writeValueAsBytes(userDTO))
            .exchange()
            .expectStatus().isBadRequest();
  <%_ } else { _%>
        restUserMockMvc.perform(put("/api/admin/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content(om.writeValueAsBytes(userDTO))<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isBadRequest());
  <%_ } _%>
    }

    @Test
  <%_ if (databaseTypeSql && !reactive) { _%>
    @Transactional
  <%_ } _%>
    void deleteUser()<% if (!reactive) { %> throws Exception<% } %> {
        // Initialize the database
        userRepository.<%= saveMethod %>(user)<% if (reactive) { %>.block()<% } %>;
        int databaseSizeBeforeDelete = userRepository.findAll()<% if (reactive) { %>
            .collectList().block()<% } %>.size();

        // Delete the user
  <%_ if (reactive) { _%>
        webTestClient.delete().uri("/api/admin/users/{login}", user.getLogin())
            .accept(MediaType.APPLICATION_JSON)
            .exchange()
            .expectStatus().isNoContent();
  <%_ } else { _%>
        restUserMockMvc.perform(delete("/api/admin/users/{login}", user.getLogin())
            .accept(MediaType.APPLICATION_JSON)<% if (authenticationUsesCsrf) { %>
            .with(csrf())<% } %>)
            .andExpect(status().isNoContent());
  <%_ } _%>
  <%_ if (cacheProviderAny) { _%>

        assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin(), <%= user.persistClass %>.class)).isNull();
  <%_ } _%>

        // Validate the database is empty
        assertPersistedUsers(users -> assertThat(users).hasSize(databaseSizeBeforeDelete - 1));
    }
<%_ } _%>

    @Test
    void testUserEquals() throws Exception {
        TestUtil.equalsVerifier(<%= user.persistClass %>.class);
        <%= user.persistClass %> user1 = new <%= user.persistClass %>();
        user1.setId(DEFAULT_ID);
        <%= user.persistClass %> user2 = new <%= user.persistClass %>();
        user2.setId(user1.getId());
        assertThat(user1).isEqualTo(user2);
        user2.setId(<%- user.primaryKey.javaSampleValues[1] %>);
        assertThat(user1).isNotEqualTo(user2);
        user1.setId(null);
        assertThat(user1).isNotEqualTo(user2);
    }

    private void assertPersistedUsers(Consumer<List<<%= user.persistClass %>>> userAssertion) {
<%_ if (databaseTypeCouchbase) { _%>
        // The security filter chain clears the security context after remote calls
        SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
<%_ } _%>
        userAssertion.accept(userRepository.findAll()<% if (reactive) { %>.collectList().block()<% } %>);
    }
}
